<template>
  <div class="analysis-page">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card title="房价数据分析" :bordered="false">
          <a-form layout="inline">
            <a-form-item label="选择城市">
              <a-select
                v-model:value="selectedCity"
                style="width: 120px"
                placeholder="选择城市"
                @change="handleCityChange"
              >
                <a-select-option v-for="city in cities" :key="city" :value="city">
                  {{ city }}
                </a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="fetchAnalysisData" :loading="loading">
                分析
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCity">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="房源总数"
            :value="cityStatistics.houseCount"
            :loading="loading"
          >
            <template #suffix>
              <home-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="平均总价"
            :value="cityStatistics.avgPrice"
            :precision="2"
            :loading="loading"
            suffix="万元"
          >
            <template #prefix>
              <money-collect-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="平均单价"
            :value="cityStatistics.avgUnitPrice"
            :precision="2"
            :loading="loading"
            suffix="万元/㎡"
          >
            <template #prefix>
              <rise-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="平均面积"
            :value="cityStatistics.avgArea"
            :precision="1"
            :loading="loading"
            suffix="㎡"
          >
            <template #prefix>
              <column-width-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCity">
      <a-col :span="12">
        <a-card :bordered="false" title="价格分布">
          <div ref="priceDistChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card :bordered="false" title="面积分布">
          <div ref="areaDistChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCity">
      <a-col :span="12">
        <a-card :bordered="false" title="户型分布">
          <div ref="layoutDistChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card :bordered="false" title="装修分布">
          <div ref="decorationDistChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCity">
      <a-col :span="24">
        <a-card :bordered="false" title="价格-面积散点图">
          <div ref="scatterChartRef" style="width: 100%; height: 500px"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { useHouseStore } from '../stores/houseStore'
import { useAnalysisStore } from '../stores/analysisStore'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  HomeOutlined,
  MoneyCollectOutlined,
  RiseOutlined,
  ColumnWidthOutlined
} from '@ant-design/icons-vue'

const route = useRoute()
const houseStore = useHouseStore()
const analysisStore = useAnalysisStore()

// 状态
const loading = ref(false)
const selectedCity = ref('')
const cities = ref([])
const cityStatistics = ref({
  houseCount: 0,
  avgPrice: 0,
  avgUnitPrice: 0,
  avgArea: 0
})

// 图表引用
const priceDistChartRef = ref(null)
const areaDistChartRef = ref(null)
const layoutDistChartRef = ref(null)
const decorationDistChartRef = ref(null)
const scatterChartRef = ref(null)

// 图表实例
let priceDistChart = null
let areaDistChart = null
let layoutDistChart = null
let decorationDistChart = null
let scatterChart = null

// 处理城市变化
const handleCityChange = (value) => {
  selectedCity.value = value
  fetchAnalysisData()
}

// 获取分析数据
const fetchAnalysisData = async () => {
  if (!selectedCity.value) {
    message.warning('请选择城市')
    return
  }
  
  loading.value = true
  
  try {
    // 获取城市统计数据
    const stats = await analysisStore.fetchCityStatistics(selectedCity.value)
    cityStatistics.value = {
      houseCount: stats.houseCount || 0,
      avgPrice: stats.avgPrice?.toFixed(2) || 0,
      avgUnitPrice: stats.avgUnitPrice?.toFixed(2) || 0,
      avgArea: stats.avgArea?.toFixed(1) || 0
    }
    
    // 获取价格分布数据
    const priceDistribution = await analysisStore.fetchPriceDistribution(selectedCity.value)
    
    // 获取面积分布数据
    const areaDistribution = await analysisStore.fetchAreaDistribution(selectedCity.value)
    
    // 获取户型分布数据
    const layoutDistribution = await analysisStore.fetchLayoutDistribution(selectedCity.value)
    
    // 获取装修分布数据
    const decorationDistribution = await analysisStore.fetchDecorationDistribution(selectedCity.value)
    
    // 获取价格-面积散点图数据
    const scatterData = await analysisStore.fetchPriceAreaScatter(selectedCity.value)
    
    // 更新图表
    nextTick(() => {
      initPriceDistChart(priceDistribution)
      initAreaDistChart(areaDistribution)
      initLayoutDistChart(layoutDistribution)
      initDecorationDistChart(decorationDistribution)
      initScatterChart(scatterData)
    })
  } catch (error) {
    console.error('获取分析数据失败:', error)
    message.error('获取分析数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化价格分布图表
const initPriceDistChart = (data) => {
  if (!priceDistChartRef.value) return
  
  priceDistChart = echarts.init(priceDistChartRef.value)
  
  // 数据格式兼容处理
  let ranges = []
  let values = []
  
  if (data && data.ranges && data.counts && Array.isArray(data.ranges) && Array.isArray(data.counts)) {
    // 后端返回的新格式
    ranges = data.ranges
    values = data.counts
  } else if (data && data.data && Array.isArray(data.data)) {
    // 后端返回的饼图格式
    ranges = data.data.map(item => item.name)
    values = data.data.map(item => item.value)
  } else if (data && typeof data === 'object') {
    // 原始对象格式
    ranges = Object.keys(data)
    values = ranges.map(range => data[range])
  } else {
    console.error('价格分布数据格式不正确:', data)
    return
  }
  
  const option = {
    title: {
      text: '价格分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ranges,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '房源数量'
    },
    series: [
      {
        name: '价格分布',
        type: 'bar',
        data: values,
        itemStyle: {
          color: function(params) {
            const colorList = ['#1890ff', '#36cfc9', '#52c41a', '#fadb14', '#fa8c16', '#f5222d']
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }
  
  priceDistChart.setOption(option)
}

// 初始化面积分布图表
const initAreaDistChart = (data) => {
  if (!areaDistChartRef.value) return
  
  areaDistChart = echarts.init(areaDistChartRef.value)
  
  // 数据格式兼容处理
  let ranges = []
  let values = []
  
  if (data && data.labels && data.counts && Array.isArray(data.labels) && Array.isArray(data.counts)) {
    // 后端返回的新格式
    ranges = data.labels
    values = data.counts
  } else if (data && data.data && Array.isArray(data.data)) {
    // 后端返回的饼图格式
    ranges = data.data.map(item => item.name)
    values = data.data.map(item => item.value)
  } else if (data && typeof data === 'object') {
    // 原始对象格式
    ranges = Object.keys(data)
    values = ranges.map(range => data[range])
  } else {
    console.error('面积分布数据格式不正确:', data)
    return
  }
  
  const option = {
    title: {
      text: '面积分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ranges,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '房源数量'
    },
    series: [
      {
        name: '面积分布',
        type: 'bar',
        data: values,
        itemStyle: {
          color: function(params) {
            const colorList = ['#13c2c2', '#52c41a', '#fadb14', '#fa8c16', '#f5222d', '#722ed1']
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }
  
  areaDistChart.setOption(option)
}

// 初始化户型分布图表
const initLayoutDistChart = (data) => {
  if (!layoutDistChartRef.value) return
  
  layoutDistChart = echarts.init(layoutDistChartRef.value)
  
  // 数据格式兼容处理
  let layouts = []
  let values = []
  let pieData = []
  
  if (data && data.layouts && data.counts && Array.isArray(data.layouts) && Array.isArray(data.counts)) {
    // 后端返回的新格式
    layouts = data.layouts
    values = data.counts
    pieData = layouts.map((layout, index) => ({
      value: values[index],
      name: layout
    }))
  } else if (data && data.data && Array.isArray(data.data)) {
    // 后端返回的饼图格式
    pieData = data.data
    layouts = data.data.map(item => item.name)
    values = data.data.map(item => item.value)
  } else if (data && typeof data === 'object') {
    // 原始对象格式
    layouts = Object.keys(data)
    values = layouts.map(layout => data[layout])
    pieData = layouts.map((layout, index) => ({
      value: values[index],
      name: layout
    }))
  } else {
    console.error('户型分布数据格式不正确:', data)
    return
  }
  
  const option = {
    title: {
      text: '户型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: layouts
    },
    series: [
      {
        name: '户型分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  layoutDistChart.setOption(option)
}

// 初始化装修分布图表
const initDecorationDistChart = (data) => {
  if (!decorationDistChartRef.value) return
  
  decorationDistChart = echarts.init(decorationDistChartRef.value)
  
  // 数据格式兼容处理
  let decorations = []
  let values = []
  let pieData = []
  
  if (data && data.decorations && data.counts && Array.isArray(data.decorations) && Array.isArray(data.counts)) {
    // 后端返回的新格式
    decorations = data.decorations
    values = data.counts
    pieData = decorations.map((decoration, index) => ({
      value: values[index],
      name: decoration
    }))
  } else if (data && data.data && Array.isArray(data.data)) {
    // 后端返回的饼图格式
    pieData = data.data
    decorations = data.data.map(item => item.name)
    values = data.data.map(item => item.value)
  } else if (data && typeof data === 'object') {
    // 原始对象格式
    decorations = Object.keys(data)
    values = decorations.map(decoration => data[decoration])
    pieData = decorations.map((decoration, index) => ({
      value: values[index],
      name: decoration
    }))
  } else {
    console.error('装修分布数据格式不正确:', data)
    return
  }
  
  const option = {
    title: {
      text: '装修分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: decorations
    },
    series: [
      {
        name: '装修分布',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  decorationDistChart.setOption(option)
}

// 初始化价格-面积散点图
const initScatterChart = (data) => {
  if (!scatterChartRef.value) return
  
  scatterChart = echarts.init(scatterChartRef.value)
  
  // 数据格式兼容处理
  let scatterData = []
  
  // 检查数据结构并进行适当处理
  if (data && data.areas && data.prices && Array.isArray(data.areas) && Array.isArray(data.prices)) {
    // 处理后端返回的数组格式数据
    scatterData = data.areas.map((area, index) => {
      const price = data.prices[index] || 0
      const unitPrice = area > 0 ? price / area : 0
      return [area, price, unitPrice]
    })
  } else if (data && Array.isArray(data)) {
    // 处理直接的数组格式数据
    scatterData = data.map(item => {
      if (typeof item === 'object' && item !== null) {
        const area = item.area || 0
        const price = item.price || 0
        const unitPrice = area > 0 ? price / area : 0
        return [area, price, unitPrice]
      }
      return item
    })
  } else {
    console.error('散点图数据格式不正确:', data)
    return
  }
  
  const option = {
    title: {
      text: '房价与面积关系散点图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        return `面积: ${params.value[0]}㎡<br/>总价: ${params.value[1]}万元<br/>单价: ${params.value[2].toFixed(2)}万元/㎡`
      }
    },
    xAxis: {
      type: 'value',
      name: '面积(㎡)',
      nameLocation: 'end',
      min: 0
    },
    yAxis: {
      type: 'value',
      name: '总价(万元)',
      nameLocation: 'end',
      min: 0
    },
    visualMap: {
      min: 0,
      max: 5,
      dimension: 2,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '5%',
      text: ['高单价', '低单价'],
      inRange: {
        color: ['#52c41a', '#fadb14', '#fa8c16', '#f5222d']
      }
    },
    series: [
      {
        name: '价格-面积',
        type: 'scatter',
        symbolSize: 8,
        data: scatterData
      }
    ]
  }
  
  scatterChart.setOption(option)
}

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  priceDistChart?.resize()
  areaDistChart?.resize()
  layoutDistChart?.resize()
  decorationDistChart?.resize()
  scatterChart?.resize()
})

// 监听路由参数变化
watch(() => route.query, (query) => {
  if (query.city) {
    selectedCity.value = query.city
    fetchAnalysisData()
  }
}, { immediate: true })

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 获取城市列表
    const citiesList = await houseStore.fetchCities()
    cities.value = citiesList
    
    // 如果URL中没有指定城市，默认选择第一个城市
    if (!selectedCity.value && cities.value.length > 0) {
      selectedCity.value = cities.value[0]
      await fetchAnalysisData()
    }
  } catch (error) {
    console.error('获取城市列表失败:', error)
    message.error('获取城市列表失败')
  }
})
</script>

<style scoped lang="scss">
.analysis-page {
  padding: 24px;
}
</style> 